<?php
session_start();

if(isset($_SESSION['authorised']) && $_SESSION['authorised'] == true)
{   
    if(isset($_SESSION['type']))
    {
        if($_SESSION['type'] == 'administrator')
        {
        	include('connection.inc');
			$paid_by=addslashes(pg_escape_string($_POST['paid_by']));
			$amount=addslashes(pg_escape_string($_POST['amount']));
			$sql = "SELECT usertype FROM users where username='$paid_by'";
			$result = pg_query($sql);
			$usertype = pg_fetch_result($result, $i, 'usertype');
			$description=addslashes(pg_escape_string($_POST['description']));
            
			/**if(isset($_POST['paid_tag']) && $_POST['paid_tag'] == 'true') {
				$paid_tag = 'true';
			}
			else {
				$paid_tag = 'false';
			}**/
			
			if($amount==''||$description=='')
            {
            	$_SESSION['error']='Error in creating transaction. Put information in all fields.';
				header('Location:admin_alert.php');
                exit();
            }
			
            
            $sql="INSERT INTO transactions (username, amount, description, transaction_date) VALUES ('$paid_by', '$amount', '$description', localtimestamp)";
			$result=pg_query($sql);
			
			if($usertype=='tutor')
			{
				$sql = "SELECT teacher_id FROM teachers where username='$paid_by'";
				$result = pg_query($sql);
				$teacher_id = pg_fetch_result($result, 0, 'teacher_id');
				$sql = "update teachers set salary=(salary-$amount) where teacher_id=$teacher_id";
				$result = pg_query($sql);
			}
			elseif($usertype=='student')
			{
				$sql = "SELECT student_id FROM students where username='$paid_by'";
				$result = pg_query($sql);
				$student_id = pg_fetch_result($result, 0, 'student_id');
				$sql = "update students set payment=(payment-$amount) where student_id=$student_id";
				$result = pg_query($sql);
			}
			header('Location: admin_managetransactions.php');
			exit();
        }
        elseif($_SESSION['type'] == 'student')
        {
            header('Location: student_index.php');
            exit();
        }
        elseif($_SESSION['type'] == 'tutor')
        {
            header('Location: tutor_index.php');
            exit();
        }
        elseif($_SESSION['type'] == 'parent')
        {
            header('Location: parent_index.php');
            exit();
        }
    }
}
else
{
    header('Location: index.php');
}
?>
